package com.atguigu.lease.web.service.impl;

import com.atguigu.lease.constant.RedisConstant;
import com.atguigu.lease.exception.LeaseException;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.result.ResultCodeEnum;
import com.atguigu.lease.utils.JwtUtil;
import com.atguigu.lease.web.service.LoginService;
import com.atguigu.lease.web.service.SystemUserService;
import com.atguigu.lease.web.vo.login.CaptchaVo;
import com.atguigu.lease.web.vo.login.LoginVo;
import com.atguigu.lease.web.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.jsonwebtoken.Claims;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SystemUserService systemUserService;

    @Override
    public CaptchaVo customGetCaptcha() {
        // 生成验证码图片
        // 宽 130 高 140 长度 4
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 140, 4);
        // 默认 字母数字混合
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
        // 获取验证码图片
        String imgStr = specCaptcha.toBase64();
        // 正确验证码
        String code = specCaptcha.text();

        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(key, code, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);

        return new CaptchaVo(imgStr, key);
    }

    @Override
    public String customLogin(LoginVo loginVo) {
        // 校验验证码
        String redisCode = (String) redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if (StringUtils.isEmpty(redisCode)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        if (!redisCode.equalsIgnoreCase(loginVo.getCaptchaCode())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        // 检查账号
        SystemUser systemUser = systemUserService.getOne(new LambdaQueryWrapper<SystemUser>().eq(SystemUser::getUsername, loginVo.getUsername()));
        if (systemUser == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        // 检查密码
        if (!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        // 账号是否可用
        if (systemUser.getStatus().equals(BaseStatus.DISABLE)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        // 生成token
        return JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
    }

    @Override
    public SystemUserInfoVo customInfo(String accessToken) {
        Claims claims = JwtUtil.parseToken(accessToken);
        // 存在类型转换异常 jwt -> long -> userId -> int
        Long userId = claims.get("userId", Long.class);
        SystemUser systemUser = systemUserService.getById(userId);
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        BeanUtils.copyProperties(systemUser, systemUserInfoVo);
        return systemUserInfoVo;
    }
}
